package com.kye.express.business.share;

import android.app.ProgressDialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityShareBinding;
import com.kye.express.view.ToastManager;
import com.oxbix.spanlogistics.share.ShareBean;
import com.oxbix.spanlogistics.share.ShareHelper;
import com.oxbix.spanlogistics.share.config.ImageConfigs;
import com.oxbix.spanlogistics.share.services.RetrofitAPIService;
import com.oxbix.spanlogistics.share.sina.SINAEntryActivity;
import com.oxbix.spanlogistics.share.tencent.TencentShareHelper;
import com.oxbix.spanlogistics.utils.FileUtils;
import com.tencent.tauth.Tencent;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ShareActivity extends BaseAppCompatActivity implements ShareContract.ShareView {

    private ActivityShareBinding mBinding;
    private int mType;
    private ShareBean mShareBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_share);

        initEvent();
        initData();
    }

    private void initEvent() {
        setSupportActionBar(mBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        RxToolbar.navigationClicks(mBinding.toolbar)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        finish();
                    }
                });

        RxView.clicks(mBinding.superTextViewWechat).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                shareByType(0);
            }
        });

        RxView.clicks(mBinding.superTextViewWechatMoment).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                shareByType(1);
            }
        });

        RxView.clicks(mBinding.superTextViewQq).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                shareByType(2);
            }
        });

        RxView.clicks(mBinding.superTextViewQqZone).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                shareByType(3);
            }
        });

        RxView.clicks(mBinding.superTextViewSinaWeibo).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                shareByType(4);
            }
        });

    }

    private void initData() {
        Glide.with(this)
                .load(R.drawable.icon_share_qr_code)
                .into(mBinding.imageViewQrCode);
    }

    public void shareByType(int type) {
        ShareBean shareBean = new ShareBean();
        shareBean.setTitle("kye");
        shareBean.setLinkUrl("http://www.baidu.com");
        shareBean.setSummary("跨越速运 一诺定达");
        shareBean.setUrl(ImageConfigs.IMAGES[0]);
        getBitmapFromUrl(shareBean, type);
    }

    public void getBitmapFromUrl(final ShareBean shareBean, final int type) {
        mShareBean = shareBean;
        this.mType = type;

        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle("加载图片中 请稍后...");
        dialog.show();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ImageConfigs.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build();
//        RetrofitAPIService apiService = RetrofitManager.getInstance().createService(RetrofitAPIService.class);
        RetrofitAPIService apiService = retrofit.create(RetrofitAPIService.class);

        apiService.queryImage(shareBean.getUrl())
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        String path = null;
                        if (responseBody != null && responseBody.byteStream() != null) {
                            Bitmap bitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                            com.blankj.utilcode.utils.FileUtils.createOrExistsFile(FileUtils.getDownloadFilePath() + File.separator + "share.png");

                            boolean isSuccess = FileUtils.saveBitmapInFile(bitmap, FileUtils.getDownloadFilePath() + File.separator + "share.png");
                            if (isSuccess) {
                                path = FileUtils.getDownloadFilePath() + File.separator + "share.png";
                            }
                        }
                        return path;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {


                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String path) {
                        if (path != null) {
                            ToastManager.show(ShareActivity.this, "图片下载成功", Toast.LENGTH_SHORT);
//                            Glide.with(ShareActivity.this).load(new File(path)).into(mImageView);
                            mShareBean.setPath(path);

                            switch (type) {
                                case 0:
                                    ShareHelper.getInstance().init(ShareActivity.this).shareWechat(shareBean);
                                    break;
                                case 1:
                                    ShareHelper.getInstance().init(ShareActivity.this).shareWechatCirlcle(shareBean);
                                    break;
                                case 2:
                                    ShareHelper.getInstance().init(ShareActivity.this).shareQQ(shareBean);
                                    break;
                                case 3:
                                    ShareHelper.getInstance().init(ShareActivity.this).shareQQZone(shareBean);
                                    break;
                                case 4:
                                    Intent intent = new Intent(ShareActivity.this, SINAEntryActivity.class);
                                    intent.putExtra(ShareBean.class.getName(), shareBean);
                                    startActivity(intent);
                                    break;
                            }
                        } else {
                            ToastManager.show(ShareActivity.this, "图片下载失败", Toast.LENGTH_SHORT);
                        }
                        dialog.dismiss();
                    }


                    @Override
                    public void onError(Throwable e) {
                        ToastManager.show(ShareActivity.this, "图片下载失败");
                        Log.e("query", e.getMessage());
                        dialog.dismiss();
                    }

                    @Override
                    public void onComplete() {
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, TencentShareHelper.getInstace().tencentRequestListener);
    }

}
